// 控制页面登录权限 路由导航守卫

import router from '@/router/index'

import store from '@/store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 白名单
const whiteList = ['/404', '/login']

// 全局前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    // 有token
    // 如果数据存在就不发请求
    if (!store.getters.userInfo.id) {
      // 获取用户资料
      await store.dispatch('user/getUserInfo')
    }
    if (to.path === '/login') {
      // 登录了访问登录页面进主页
      next('/')
    } else {
      next()
    }
  } else {
    // 无touken
    if (whiteList.indexOf(to.path) === -1) {
      next('/login')
    } else {
      next()
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
